#ifndef SPEECHMANAGER_H
#define SPEECHMANAGER_H

#include <QObject>
#include <QString>
#include <QTimer>
#include <QMutex>
#include <QThread>
#include <QAudioInput>
#include <QAudioOutput>
#include <QBuffer>
#include <QProcess>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTemporaryFile>
#include <QDir>
#include <QFile>
#include <QDateTime>


class AdvancedSpeechEngine;
class BaiduSpeechClient;
class BaiduOfficialClient;
class BaiduTTSClient;

class SpeechManager : public QObject
{
    Q_OBJECT

public:
    explicit SpeechManager(QObject *parent = nullptr);
    ~SpeechManager();

    // 音频特征结构体
    struct AudioFeatures {
        double energy;          // 能量
        double pitch;           // 基频
        double tonalVariation;  // 音调变化
        double duration;        // 持续时间
    };

    enum SpeechEngine {
        EngineBaidu,
        EngineAdvanced,
        EngineOffline
    };

    enum SpeechState {
        StateIdle,
        StateListening,
        StateRecognizing,
        StateSynthesizing,
        StateError
    };
    
    // TTS播放状态
    bool m_isTTSPlaying;

public slots:
    void startListening();
    void stopListening();
    void synthesizeText(const QString &text);
    void setEngine(SpeechEngine engine);
    void setVolume(int volume);
    void setSpeed(int speed);

signals:
    void speechRecognized(const QString &text);
    void speechError(const QString &error);
    void synthesisFinished();
    void ttsFinished();
    void wakeWordDetected();
    void stateChanged(SpeechState state);
    void audioLevelChanged(double level);

private slots:
    // 删除科大讯飞相关槽函数 - 使用系统TTS替代

    void onAdvancedSpeechResult(const QString &text);
    void onAdvancedSpeechError(const QString &error);
    void onAdvancedTTSFinished();
    
    // 百度语音识别槽函数
    void onBaiduRecognitionResult(const QString &text);
    void onBaiduRecognitionError(const QString &error);
    
    // 百度官方SDK槽函数
    void onBaiduOfficialRecognitionResult(const QString &text);
    void onBaiduOfficialRecognitionError(const QString &error);
    
    // 百度TTS槽函数
    void onBaiduTTSStarted();
    void onBaiduTTSFinished();
    void onBaiduTTSError(const QString &error);

    void onAudioDataReady();
    void updateAudioLevel();
    void processVoiceRecognition();

private:
    void initializeEngines();
    void initializeAudioDevices();
    void switchToFallbackEngine();
    bool isEngineAvailable(SpeechEngine engine);
    void setState(SpeechState state);
    
    // 音频处理方法
    bool checkMicrophonePermission();
    void startAudioRecording();
    void stopAudioRecording();
    void calculateAudioLevel(const QByteArray &audioData);
    void useSystemTTS(const QString &text);
    void useNextTTSEngine(const QString &text);
    
    // 简单语音识别方法
    void startSimpleVoiceRecognition();
    void stopSimpleVoiceRecognition();
    
    // 音频特征提取和识别方法
    QString performVoiceRecognition(const QByteArray &audioData);
    AudioFeatures extractAudioFeatures(const QByteArray &audioData);
    double estimatePitch(const qint16 *samples, int sampleCount);
    double calculateSimilarity(const AudioFeatures &f1, const AudioFeatures &f2);
    
    // 多种语音识别方法
    QString trySystemSpeechRecognition(const QByteArray &audioData);
    QString tryOnlineSpeechRecognition(const QByteArray &audioData);
    // 删除trySimpleCommandMatching方法声明 - 只保留纯语音转文字功能
    // 删除百度API声明 - 使用简化的语音识别
    
    // 音频格式转换
    bool saveAudioToWavFile(const QByteArray &audioData, const QString &filename);
    QString convertAudioToBase64(const QByteArray &audioData);

    // 语音引擎
    AdvancedSpeechEngine *m_advancedEngine;
    BaiduSpeechClient *m_baiduClient;
    BaiduOfficialClient *m_baiduOfficialClient;
    BaiduTTSClient *m_baiduTTSClient;
    
    // 当前引擎和状态
    SpeechEngine m_currentEngine;
    SpeechEngine m_preferredEngine;
    SpeechState m_currentState;
    
    // 设置
    int m_volume;
    int m_speed;
    bool m_isInitialized;
    
    // 线程安全
    QMutex m_mutex;
    
    // 故障恢复
    QTimer *m_retryTimer;
    QTimer *m_audioLevelTimer;
    int m_retryCount;
    static const int MAX_RETRY_COUNT = 3;
    
    // 音频设备
    QAudioInput *m_audioInput;
    QAudioOutput *m_audioOutput;
    QIODevice *m_inputDevice;
    QIODevice *m_outputDevice;
    QBuffer *m_audioBuffer;
    double m_currentAudioLevel;
    
    // 简单语音识别
    QTimer *m_voiceRecognitionTimer;
    qint64 m_recognitionStartTime;
    
    // 网络请求
    QNetworkAccessManager *m_networkManager;
    
    // 备用识别用的音频数据
    QByteArray m_lastAudioData;
};

#endif // SPEECHMANAGER_H 